// pages/putForwardPrice/putForwardPrice.js
var app = getApp();
var isRepeat = false;

let isSend = false;
let timer = '';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    prohibit: false,
    isChoose: true, //未选择提现账户
    cards: [{
      type: 1,
      bankname: '支付宝'
    },
    {
      type: 2,
      bankname: '微信'
    },
    {
      type: 3,
      bankname: '工商银行   储蓄卡（0123）'
    },
    ],
    allMoney: '',
    page: 1,
    row: 99,
    index: [],
    userInfo: [],
    total: '',
    money: 0,
    poundage: 0,

    bank_id: '',
    isForward: false,//是否能提现

    codeShow: false, //验证弹窗
    accountType: '', //账户类型 1 银行卡，2 微信零钱
    is_phone: false, //是否已授权手机号码
    auth_phone: '', //授权的用户信息
    inputIndex: 0, //聚焦索引
    inputValue: '', //输入验证码value
    inputArr: [], //验证码分割后的数组
    codeShow: false, //验证弹窗
    sms_txt: '',//短信提示
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getWithdrawType();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.bankList();
    this.getInfo();
    isRepeat = false;
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  // 选择提现账户
  choosecard: function () {
    this.setData({
      prohibit: true
    })
  },

  // 关闭弹窗
  closemodel: function () {
    this.setData({
      prohibit: false
    })
  },
  //全部提现
  all(e) {
    var that = this;
    if (that.data.accountType == 1) {
      //扣除1%的手续费
      var tmp = Math.floor(parseFloat(that.data.userInfo.account_balance * 1000)) / 1000 * 0.99;
      tmp = Math.floor(parseFloat(tmp * 1000)) / 1000;
      var poundage = Math.floor(parseFloat(that.data.userInfo.account_balance * 1000)) / 1000 * 0.01;
      poundage = Math.floor(parseFloat(poundage * 1000)) / 1000
      that.setData({
        allMoney: tmp,
        total: 0,
        poundage: poundage,
        money: that.data.userInfo.account_balance,
        isForward: that.data.accountType ? true : false
      })
    } else {
      that.setData({
        allMoney: that.data.userInfo.account_balance,
        total: 0,
        poundage: 0,
        money: that.data.userInfo.account_balance,
        isForward: that.data.accountType ? true : false
      })
    }
  },
  //输入金额
  inputMoney(e){
    var val = e.detail.value;
    this.getMoney(val);
  },
  //计算金额
  getMoney(value) {
    var that = this;
    //账户余额
    var account_balance = that.data.userInfo.account_balance;
    //输入金额
    var val = value;

    if (that.data.accountType == 1) {
      //最大提现额度包含手续费
      var max_num = Math.floor(parseFloat(account_balance * 1000)) / 1000 * 0.99;
      max_num = Math.floor(parseFloat(max_num * 1000)) / 1000;
      if ((Math.floor(parseFloat(val * 1000)) / 1000) > max_num) {
        app.showToast('最大提现额度为：' + max_num);
        that.setData({
          allMoney: '',
          poundage: 0,
          money: 0,
          total: account_balance,
          isForward: false
        });
      } else {
        //只保留小数后三位，从点起四位
        if (val.substring(val.indexOf('.')).length <= 4) {
          var old = Math.floor(parseFloat(account_balance * 1000)) / 1000;
          var newn = Math.floor(parseFloat(val * 1000)) / 1000;
          var diff = old - newn;
          if (isNaN(diff)) {
            diff = Math.floor(parseFloat(account_balance * 1000)) / 1000;
          }
          if (diff == 0) {
            var allMoney = val * 0.99;
            allMoney = Math.floor(parseFloat(allMoney * 1000)) / 1000;
            var total = diff;
          } else {
            var allMoney = val;
            var total = diff - val * 0.01;
            total = Math.floor(parseFloat(total * 1000)) / 1000;
          }
          var poundage = Math.floor(parseFloat(val * 1000)) / 1000 * 0.01;
          poundage = Math.floor(parseFloat(poundage * 1000)) / 1000
          that.setData({
            allMoney: allMoney,
            total: total,
            money: val,
            poundage: poundage,
            isForward: val && that.data.accountType ? true : false
          });
        } else {
          //超出的丢弃
          var len = val.length - (val.substring(val.indexOf('.')).length - 4);
          that.setData({
            allMoney: val.substring(0, len),
            isForward: val && that.data.accountType ? true : false
          });
        }
      }
    } else {
      //最大提现额度不能超过总余额
      var max_num = Math.floor(parseFloat(account_balance * 1000)) / 1000;
      max_num = Math.floor(parseFloat(max_num * 1000)) / 1000;
      if ((Math.floor(parseFloat(val * 1000)) / 1000) > max_num) {
        app.showToast('最大提现额度为：' + account_balance);
        that.setData({
          allMoney: '',
          poundage: 0,
          money: 0,
          total: account_balance,
          isForward: false
        });
      } else {
        var old = Math.floor(parseFloat(account_balance * 1000));
        var newn = Math.floor(parseFloat(val * 1000));
        var diff = (old - newn) / 1000;
        if (isNaN(diff)) {
          diff = Math.floor(parseFloat(account_balance * 1000)) / 1000;
        }
        var allMoney = val;
        var total = diff;
        that.setData({
          allMoney: allMoney,
          total: total,
          money: val,
          poundage: 0,
          isForward: val && that.data.accountType ? true : false
        });
      }
    }
  },
  // 选择银行卡
  cardItem: function (e) {
    var bank_id = e.currentTarget.dataset.id;
    this.setData({
      prohibit: false,
      isChoose: false,
      index: e.currentTarget.dataset.index,
      bank_id: bank_id,
      accountType: 1, //账户类型
      isForward: this.data.allMoney ? true : false
    });
    if (this.data.allMoney != '') {
      this.getMoney(this.data.allMoney);
    }
  },
  // 选择微信
  wxItem() {
    this.setData({
      prohibit: false,
      isChoose: false,
      accountType: 2, //账户类型
      isForward: this.data.allMoney ? true : false
    });
    if (this.data.allMoney != '') {
      this.getMoney(this.data.allMoney);
    }
  },
  // 获取提现账户配置
  getWithdrawType() {
    var that = this;
    app.ajax({
      url: "Common/Common/getWithdrawType",
      data: {},
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            withdraw_config: res.data.data
          })
        }
      }
    })
  },
  bankList() {
    var that = this;
    app.ajax({
      url: 'Salesman/Account/bankList',
      method: "POST",
      data: {
        page: that.data.page,
        row: that.data.row
      },
      success: function (res) {
        var flag = res.data;
        if (flag.code < 0) {
          app.showToast(flag.message);
          return false;
        }
        // var tmp = flag.data.data[0];
        // tmp.p_sn = tmp.p_sn.substring(tmp.p_sn.length - 4);
        // that.setData({
        //   cards: flag.data.data,
        //   index: tmp
        // });

        var accountType = '';
        var chooseItem = '';
        var bankId = '';
        var isChoose = true;
        // 如果有银行卡提现权限，默认选中第一张的银行卡
        if (that.data.withdraw_config.bank.switch && flag.data.data.length > 0) {
          bankId = flag.data.data[0].bank_id;
          accountType = 1;
          chooseItem = flag.data.data[0];
          isChoose = false;
        } else if (that.data.withdraw_config.weixin.switch) {
          accountType = 2;
          isChoose = false;
        }
        that.setData({
          cards: flag.data.data,
          index: chooseItem,
          bank_id: bankId,
          accountType,
          isChoose
        })
      }
    })
  },
  //获取账户余额
  getInfo() {
    var that = this;
    app.ajax({
      url: 'Salesman/Login/getInfo',
      data: {},
      success: function (res) {
        // console.log(res)
        if (res.data.code == 1000) {
          that.setData({
            userInfo: res.data.data,
            total: res.data.data.account_balance
          })
        }
      }
    });
  },
  //添加银行卡
  navAddCard() {
    wx.navigateTo({
      url: '../addeditAccount/addeditAccount?type=2',
    })
  },
  // 授权手机号码
  bindPhone(e) {
    if (!this.data.isForward) {
      return false;
    }

    console.log('e', e);
    let is_phone = e.detail.iv ? true : false;
    this.setData({
      is_phone
    })
    let auth_detail = e.detail;

    var that = this;
    var reg = /^([1-9]\d*|0)(\.\d{1,3})?$/;
    if (!reg.test(that.data.allMoney)) {
      app.showToast('请输入正确的提现金额');
      return false;
    }
    if (that.data.allMoney < 50) {
      app.showToast('最低提现金额50');
      return false;
    }
    if (that.data.allMoney > 50 && that.data.allMoney % 10 != 0) {
      app.showToast('提现金额必须是10的倍数');
      return false;
    }
    if (is_phone) {
      this.getOpenID(auth_detail);
    }
    if (!is_phone) app.showToast('请授权手机号码，才能提现哦~');
  },
  //获取openid
  getOpenID(auth_detail) {
    var that = this;
    var session_key = wx.getStorageSync('session_key') || '';
    var openid = wx.getStorageSync('openid') || '';
    if (session_key) {
      that.setData({
        session_key,
        openid
      })
      that.decodePhone(auth_detail);
    } else {
      wx.login({
        success: results => {
          app.ajax({
            url: "Common/Wx/getUserOpenid",
            data: {
              code: results.code
            },
            success: res => {
              if (res.data.code == 1000) {
                that.setData({
                  session_key: res.data.data.session_key,
                  openid: res.data.data.openid
                })
                that.decodePhone(auth_detail);
              }
            }
          })
        },
        fail: e => {
        }
      })
    }

  },
  //解码手机号
  decodePhone(auth_detail) {
    console.log('auth_detail', auth_detail);
    app.ajax({
      url: 'Common/Wx/aesPhoneDecrypt',
      data: {
        session_key: this.data.session_key,
        data: auth_detail.encryptedData,
        iv: auth_detail.iv,
      },
      success: (res) => {
        console.log('res>>>>>>>>', res);
        if (res.data.code == 1000) {
          this.setData({
            auth_phone: res.data.data.phoneNumber,
            is_phone: true,
            codeShow: true
          });
          this.sendSms();
        } else {
          this.setData({
            auth_phone: '',
            is_phone: false
          });
          app.showToast(res.data.message);
        }
      }
    });
  },
  // 发送验证码
  sendSms() {
    var that = this;
    if (isSend) return;
    isSend = true;
    app.ajax({
      url: 'Common/Common/sendSms',
      data: { phone: that.data.auth_phone, },
      success: function (res) {
        that.setData({
          sms_txt: res.data.message
        })
        if (res.data.code == 1000) {
          that.setData({
            codeShow: true,
            times: 60
          });
          clearInterval(timer);
          timer = setInterval(() => {
            let times = that.data.times;
            if (times <= 0) {
              clearInterval(timer);
              that.setData({
                times: 0
              });
            } else {
              that.setData({
                times: times - 1
              });
            }
          }, 1000);
        } else {
          //app.showToast(res.data.message);
        }
        isSend = false;
      }
    });
  },
  // 数据验证码
  bindCode(e) {
    var that = this;
    var inputIndex = that.data.inputIndex;
    var value = e.detail.value;
    var inputArr = value.split('');
    console.log('inputArr', inputArr);
    var length = inputArr.length;
    that.setData({
      inputValue: value,
      inputArr: inputArr
    });
    console.log('length', length);
    console.log('inputIndex', inputIndex);
    if (length < 6) {
      that.setData({
        inputIndex: length
      });
    } else {
      that.startCash(value); // 开始提现
    }
  },
  // 关闭手机验证码弹窗
  closeCode() {
    var that = this;
    clearInterval(timer);
    that.setData({
      codeShow: false,
      inputValue: '',
      inputIndex: 0,
      inputArr: []
    });
  },
  // 提现
  newExtract() {
    var that = this;
    var reg = /^([1-9]\d*|0)(\.\d{1,3})?$/;
    if (!reg.test(that.data.allMoney)) {
      app.showToast('请输入正确的提现金额');
      return false;
    }
    if (that.data.allMoney < 50) {
      app.showToast('最低提现金额50');
      return false;
    }
    if (that.data.allMoney > 50 && that.data.allMoney % 10 != 0) {
      app.showToast('提现金额必须是10的倍数');
      return false;
    }

    this.setData({
      auth_phone: that.data.accountType==1?that.data.index.phone:that.data.auth_phone,
      codeShow: true
    });
    this.sendSms();
  },
  // 开始提现
  startCash(sms_code) {
    var that = this;
    if (isRepeat) {
      return;
    }
    isRepeat = true;

    app.ajax({
      url: "Salesman/Account/addWithdrawApply",
      data: {
        account_type: that.data.accountType,
        bank_id: that.data.accountType == 1 ? that.data.bank_id : '',
        wx_openid: that.data.accountType == 2 ? that.data.openid : '',
        money: that.data.money,
        code: sms_code,
        phone: that.data.auth_phone
      },
      success: function (res) {
        isRepeat = false;
        if (res.data.code == 1000) {
          // 关闭发送验证码弹窗
          that.setData({
            codeShow: false
          });
          app.showToast(res.data.message)
          setTimeout(function () {
            wx.navigateBack({
              delta: 1,
            })
          }, 1000);
        } else {
          app.showToast(res.data.message)
        }
      }
    })

  },
})